//
//  ReportListVC.m
//  efairy
//
//  Created by 李锋 on 2019/3/11.
//  Copyright © 2019年 East. All rights reserved.
//

#import "ReportListVC.h"
#import <MJRefresh.h>
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "EFAModel.h"
#import "ReportModel.h"
#import "ReportListCell.h"
#import "XJTimePickView.h"
#import "ReportDetailVC.h"

@interface ReportListVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property(nonatomic,strong) UITableView *tableView;//报表列表
@property(nonatomic,strong)UIView *checkDate;
@property (nonatomic,strong) UILabel *startDate;
@property (nonatomic,strong) UILabel *endDate;
@property (nonatomic, assign) int pageIndex;
@property (nonatomic, strong) MJRefreshComponent *refreshViewComponent;
@property(nonatomic,strong)UITextField *searchText;
@property(nonatomic,strong)NSString *startTime;
@property(nonatomic,strong)NSString *endTime;
@property(nonatomic,strong)NSMutableArray<ReportListModel *> *reportList;
@property (strong,nonatomic) UIView *dateContentView;
@property (strong,nonatomic) UIView *statrDateView;
@property (strong,nonatomic) UIView *endDateView;
@property (strong,nonatomic) UIButton *cancel;
@property (strong,nonatomic) UIButton *confirm;
@property (strong,nonatomic) XJTimePickView *startTimePickView;
@property (strong,nonatomic) XJTimePickView *endTimePickView;
@end

@implementation ReportListVC

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self setNavigationBar];
    [self initView];

}

- (BOOL)hidesBottomBarWhenPushed{
    return YES;
}

//-(void)setNavigationBar{
//    [self.navigationController setNavigationBarHidden:YES];
//}


-(void) initView{
    float barHeight = self.navigationController.navigationBar.frame.size.height;
    _checkDate = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    _checkDate.width = SCREEN_WIDTH;
    _checkDate.backgroundColor = [UIColor whiteColor];
    
    UITapGestureRecognizer *tapGesturRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickCheckDate:)];
    [_checkDate addGestureRecognizer:tapGesturRecognizer];
    
    
    
    _startDate = [[UILabel alloc]init];
    _startDate.text=@"开始时间";
    _startDate.textColor=ColorFromRGB(0x666666);
    _startDate.font= [UIFont systemFontOfSize:15.0];
    
    
    _endDate = [[UILabel alloc]init];
    _endDate.text=@"结束时间";
    _endDate.textColor=ColorFromRGB(0x666666);
    _endDate.font= [UIFont systemFontOfSize:15.0];
    
    
    //右箭头图标
    UIImageView *rightArrow=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 8, 13)];
    rightArrow.image=[UIImage imageNamed:@"icon_right_arrow"];
    [_checkDate sd_addSubviews:@[_startDate,_endDate,rightArrow]];
    
    
    _startDate.sd_layout.widthIs(100)
    .heightIs(15)
    .leftSpaceToView(_checkDate, 16)
    .topSpaceToView(_checkDate, 12.5);
    
    _endDate.sd_layout.widthIs(100).heightIs(15).leftSpaceToView(_startDate, 80).topSpaceToView(_checkDate, 12.5);
    
    
    rightArrow.sd_layout.heightIs(13).widthIs(8)
    .topSpaceToView(_checkDate, 13.5)
    .rightSpaceToView(_checkDate, 16);
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, 1)];
    line.backgroundColor = ColorFromRGB(0xe5e5e5);
    
    
    UIView *searchView = [[UIView alloc]initWithFrame:CGRectMake(0, 41, SCREEN_WIDTH, 40)];
    //搜索栏背景
    UIView *searchBg =  [[UIView alloc]init];
    searchBg.layer.borderWidth=0.0f;
    searchBg.layer.cornerRadius=16.0f;
    searchBg.backgroundColor = ColorFromRGB(0xefefef);
    [searchView addSubview:searchBg];
    
    //创建左侧搜索图标
    UIImageView *searchIcon=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 15, 15)];
    searchIcon.image=[UIImage imageNamed:@"search_icon"];
    [searchView addSubview:searchIcon];
    
    //文本输入框
    _searchText = [[UITextField alloc]init];
    _searchText.backgroundColor = ColorFromRGB(0xefefef);
    _searchText.clearButtonMode=UITextFieldViewModeAlways;//只要输入框有内容就出现
    // 设置提示文字
    _searchText.placeholder = @"请输项目名称";
    _searchText.layer.borderWidth=0.0f;
    _searchText.layer.cornerRadius=16.0f;
    _searchText.returnKeyType = UIReturnKeySearch;//变为搜索按钮
    _searchText.delegate = self;//设置代理
    [searchView addSubview:_searchText];
    
     UIView *line2 = [[UIView alloc]initWithFrame:CGRectMake(0, 80, SCREEN_WIDTH, 1)];
    line2.backgroundColor = ColorFromRGB(0xeff0f4);
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 81, SCREEN_WIDTH, SCREEN_HEIGHT-statusBarHeight-barHeight-122) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = ColorFromRGB(0xeff0f4);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
//    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    __weak typeof(self) weakSelf = self;
    //..下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.refreshViewComponent = weakSelf.tableView.mj_header;
        weakSelf.pageIndex = 1;
        [weakSelf queryProjectList:YES];
    }];
    
    
    //..上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.refreshViewComponent = weakSelf.tableView.mj_footer;
        weakSelf.pageIndex = weakSelf.pageIndex + 1;
        [weakSelf queryProjectList:NO];
    }];
    
    [self.view sd_addSubviews:@[_checkDate,line,searchView,line2,_tableView]];
    
   
    searchBg.sd_layout.heightIs(30)
    .topSpaceToView(searchView, 5)
    .leftSpaceToView(searchView, 16)
    .rightSpaceToView(searchView, 16);
    
    searchIcon.sd_layout.heightIs(15)
    .widthIs(15)
    .topSpaceToView(searchView, 12.5)
    .leftSpaceToView(searchView, 32);
    
    _searchText.sd_layout.heightIs(30)
    .topSpaceToView(searchView, 5)
    .leftSpaceToView(searchIcon, 12)
    .rightSpaceToView(searchView, 16);
    
    
    _startTimePickView = [self statrTimePickView];
    _endTimePickView = [self endTimePickView];
    [self setupDateChooseView];
    [self setDefaultsDate];
    [self.tableView.mj_header beginRefreshing];
    
}

-(void)setupDateChooseView{
    
    UIWindow *wd = [[UIApplication sharedApplication].windows lastObject];
    _dateContentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    //只设置黑白背景色,这种设置方式不会导致子view也跟随透明
    _dateContentView.backgroundColor =  [UIColor colorWithWhite:0.f alpha:0.5];
    
    
    _statrDateView = [[UIView alloc] initWithFrame:CGRectMake(20, 150, SCREEN_WIDTH-40, SCREEN_HEIGHT-300)];
    _statrDateView.backgroundColor =  [UIColor whiteColor];
    
    UILabel *startDateTitle = [[UILabel alloc]init];
    startDateTitle.font = [UIFont boldSystemFontOfSize:17.f];
    startDateTitle.textColor = ColorFromRGB(0x3F3F3F);
    startDateTitle.textAlignment = NSTextAlignmentCenter;
    startDateTitle.text = @"起始时间";
    
    UILabel *endDateTitle = [[UILabel alloc]init];
    endDateTitle.font = [UIFont boldSystemFontOfSize:17.f];
    endDateTitle.textColor = ColorFromRGB(0x3F3F3F);
    endDateTitle.textAlignment = NSTextAlignmentCenter;
    endDateTitle.text = @"结束时间";
    
    _startTimePickView = [self statrTimePickView];
    _endTimePickView = [self endTimePickView];
    
    _cancel = [[UIButton alloc]init];
    [_cancel setTitle:@"取消" forState:UIControlStateNormal];
    [_cancel setTitleColor:ColorFromRGB(0x999999) forState:UIControlStateNormal];
    _cancel.titleLabel.font = [UIFont boldSystemFontOfSize:16.f];
    [_cancel addTarget:self action:@selector(cancelChooseDate:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIView *vline = [[UIView alloc]init];
    vline.backgroundColor = ColorFromRGB(0xe5e5e5);
    
    UIView *hline = [[UIView alloc]init];
    hline.backgroundColor = ColorFromRGB(0xe5e5e5);
    
    
    _confirm = [[UIButton alloc]init];
    [_confirm setTitle:@"确定" forState:UIControlStateNormal];
    [_confirm setTitleColor:ColorFromRGB(0x282449) forState:UIControlStateNormal];
    _confirm.titleLabel.font = [UIFont boldSystemFontOfSize:16.f];
    [_confirm addTarget:self action:@selector(confirmChooseDate:) forControlEvents:UIControlEventTouchUpInside];
    
    [_statrDateView sd_addSubviews:@[startDateTitle,_startTimePickView,endDateTitle,_endTimePickView,hline,_cancel,vline,_confirm]];
    
    startDateTitle.sd_layout.widthIs(SCREEN_WIDTH-40)
    .heightIs(40)
    .topSpaceToView(_statrDateView, 0);
    
    _startTimePickView.sd_layout.widthIs(SCREEN_WIDTH-40)
    .heightIs((SCREEN_HEIGHT-425)/2)
    .topSpaceToView(startDateTitle, 0);
    
    endDateTitle.sd_layout.widthIs(SCREEN_WIDTH-40)
    .heightIs(40)
    .topSpaceToView(_startTimePickView, 20);
    
    _endTimePickView.sd_layout.widthIs(SCREEN_WIDTH-40)
    .heightIs((SCREEN_HEIGHT-425)/2)
    .topSpaceToView(endDateTitle, 0);
    
    hline.sd_layout.heightIs(1)
    .leftSpaceToView(_statrDateView, 0)
    .rightSpaceToView(_statrDateView,0)
    .bottomSpaceToView(_statrDateView, 44);
    
    _cancel.sd_layout.widthIs((SCREEN_WIDTH-40)/2-0.5).heightIs(44)
    .bottomSpaceToView(_statrDateView, 0);
    
    vline.sd_layout.widthIs(1).heightIs(20)
    .bottomSpaceToView(_statrDateView, 14)
    .leftSpaceToView(_cancel, 0);
    
    _confirm.sd_layout.widthIs((SCREEN_WIDTH-40)/2-0.5).heightIs(44)
    .leftSpaceToView(vline, 0)
    .bottomSpaceToView(_statrDateView, 0);
    
    [_dateContentView addSubview:_statrDateView];
    [wd addSubview:_dateContentView];
    _dateContentView.hidden = YES;
    
    
    
}


#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if(_reportList != nil && _reportList.count > 0){
        return _reportList.count;
    }
    return 0;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ReportListCell * cell = [tableView dequeueReusableCellWithIdentifier:[@"ReportListCell" description] ];
    if(!cell){
        cell = [[ReportListCell alloc]init];
        cell.layer.cornerRadius = 6;
        cell.layer.masksToBounds = YES;
        cell.delReportBlock = ^(NSInteger arrayIndex) {
            [self alertDelHint:arrayIndex];
        };
    }
    [cell setDataModel:_reportList[indexPath.section] rowIndex:indexPath.section];
    [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
    return cell;
}


#pragma mark - UITableViewDelegate

//设置section的header高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 8.f;
}

//设置section的Footer高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(_reportList && indexPath.section < _reportList.count){
        ReportDetailVC *vc = [[ReportDetailVC alloc]init];
        vc.reportId = _reportList[indexPath.section].efairyreport_id;
        [self showViewController:vc sender:nil];
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [tableView cellHeightForIndexPath:indexPath cellContentViewWidth:SCREEN_WIDTH tableView:tableView];
    
}


//设置Section的header 的view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
        return [[UIView alloc] init];
}

//设置Section的footer 的view
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
        return [[UIView alloc] init];
}



#pragma mark -UITextFieldDelegate
//搜索 这个函数是重写UITextFieldDelegate 当点击键盘搜索按钮触发
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    self.pageIndex = 1;
    [self queryProjectList:YES];
    return YES;
}

//颜值搜索栏输入的长度
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.searchText) {
        //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
        if (range.length == 1 && string.length == 0) {
            return YES;
        }
        //so easy
        else if (self.searchText.text.length >= 30) {
            self.searchText.text = [textField.text substringToIndex:30];
            return NO;
        }
    }
    return YES;
}

//停止刷新头部或者底部
- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}


- (XJTimePickView *)statrTimePickView{
    if (!_startTimePickView) {
        _startTimePickView = [[XJTimePickView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-40, (SCREEN_HEIGHT-425)/2)];
        __weak typeof(self) weakSelf = self;
        _startTimePickView.calendarChangeBlock = ^(NSString *changeTime) {
            weakSelf.startTime = changeTime;
        };
    }
    return _startTimePickView;
}

- (XJTimePickView *)endTimePickView{
    if (!_endTimePickView) {
        __weak typeof(self) weakSelf = self;
        _endTimePickView = [[XJTimePickView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-40, (SCREEN_HEIGHT-425)/2)];
        _endTimePickView.calendarChangeBlock = ^(NSString *changeTime) {
            weakSelf.endTime = changeTime;
        };
    }
    return _endTimePickView;
}



-(void)onClickCheckDate:(id)tap{
    _dateContentView.hidden = NO;
}

-(void)cancelChooseDate:(id)tap{
    _dateContentView.hidden = YES;
}

-(void)confirmChooseDate:(id)tap{
    if(!_startTime || _startTime.length < 4){
        _startTime = [NSString stringWithFormat:@"%@-%@-%@",
                      _startTimePickView.choosedYear,_startTimePickView.choosedMonth,_startTimePickView.chooseDay];
    }
    
    if(!_endTime || _endTime.length < 4){
        _endTime = [NSString stringWithFormat:@"%@-%@-%@",
                      _endTimePickView.choosedYear,_startTimePickView.choosedMonth,_startTimePickView.chooseDay];
    }
    
    _dateContentView.hidden = YES;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];//解决8小时时间差问题
    NSDate *sDate = [dateFormatter dateFromString:_startTime];
    NSDate *eDate = [dateFormatter dateFromString:_endTime];
    NSComparisonResult result =[sDate compare:eDate];
 
    switch (result) {
        case NSOrderedAscending:
            _startDate.text = _startTime;
            _endDate.text  = _endTime;
            [self.tableView.mj_header beginRefreshing];
            break;
        case NSOrderedDescending:
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"起始时间不能大于结束时间"];
            break;
        case NSOrderedSame:
            _startDate.text = _startTime;
            _endDate.text  = _endTime;
            [self.tableView.mj_header beginRefreshing];
            break;
        default:
            break;
    }
    
}



-(void)queryProjectList:(BOOL)isHeader{
    NSMutableDictionary *pars = [[NSMutableDictionary alloc]init];
    [pars setObject:@([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id) forKey:@"efairyuser_id"];
    [pars setObject:[EFAModel sharedInstance].loginInfo.access_token forKey:@"access_token"];
    if(_startTime != nil  && _startTime.length > 0){
        [pars setObject:_startTime forKey:@"start_time"];
    }
    if(_endTime != nil  && _endTime.length > 0){
        [pars setObject:_endTime forKey:@"end_time"];
    }
    if(!isHeader && _reportList && _reportList.count > 0){
        [pars setObject:_reportList[_reportList.count-1].efairyreport_id forKey:@"last_id"];
    }else{
        [pars setObject:@"0" forKey:@"last_id"];
    }
    
    [pars setObject:@"20" forKey:@"size"];
    [pars setObject:_searchText.text forKey:@"keyword"];

    
    NSLog(@"请求项参数：%@",pars);
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiReportList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求项目列表返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        //把服务端返回的json格式数据解析为对象
        ReportModel *reportModel = [ReportModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        //服务端返回本次请求的项目列表数据
        if(reportModel.report_list != nil){
            if(isHeader){
                //下拉刷新
                _reportList = reportModel.report_list;
            }else{
                //上啦加载追加数据到数组
                [_reportList addObjectsFromArray:reportModel.report_list];
            }
            if(_reportList.count >= reportModel.total_rows){
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [self.tableView.mj_footer resetNoMoreData];
            }

        }
        //刷新数据
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求项目列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}



-(void)alertDelHint:(NSInteger)arrayIndex{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"是否删除本条信息" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    
    //增加取消按钮；
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    
    //增加确定按钮；
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        [self delProject:arrayIndex];
    }];
    [alertController addAction:otherAction];
    [self presentViewController:alertController animated:true completion:nil];
}


-(void)delProject:(NSInteger)arrayIndex{
    if(!_reportList || arrayIndex >= _reportList.count){
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"数据错误！删除失败"];
        return;
    }
    NSMutableArray *reportArray = [[NSMutableArray alloc]init];
    [reportArray addObject:_reportList[arrayIndex].efairyreport_id];
    NSDictionary *parame = @{@"efairyuser_id": @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                             @"access_token":[EFAModel sharedInstance].loginInfo.access_token,
                             @"efairyreport_id_list":[reportArray yy_modelToJSONString]
                             };
    
    NSLog(@"请求项参数：%@",parame);
    [[XDAFNetworking sharedInstance] DELETE:[ApiManager apiDeleteReport] parameters:parame  success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求项目列表返回：%@", responseObject);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"删除成功"];
        [_reportList removeObjectAtIndex:arrayIndex];
        [self.tableView reloadData];
     
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求项目列表失败：%@", error);
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

-(void)setDefaultsDate{
    NSDate *currentdate = [NSDate date];
//    NSTimeInterval  days = 24 * 60 * 60 * day;  //时长
    //    NSDate *newDate = [currentdate dateByAddingTimeInterval:24 * 60 * 60  * day];
    // 减去
//    NSDate *newDate = [currentdate initWithTimeIntervalSinceNow: -days ];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy"];
    NSInteger currentYear = [[formatter stringFromDate:currentdate] integerValue];
    [formatter setDateFormat:@"MM"];
    NSInteger currentMonth = [[formatter stringFromDate:currentdate] integerValue];
    [formatter setDateFormat:@"dd"];
    NSInteger currentDay = [[formatter stringFromDate:currentdate] integerValue];
    [_startTimePickView setDefaultsDate:currentYear month:currentMonth day:currentDay];
    [_endTimePickView setDefaultsDate:currentYear month:currentMonth day:currentDay];
}

@end
